package com.zecan.blog.aspect;

import com.zecan.blog.dao.ArticleMapper;
import com.zecan.blog.service.ArticleService;
import com.zecan.blog.utils.BlogConstant;
import com.zecan.blog.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 博客文章浏览量监控,如果有人查看了文章,则进入这个aop进行保存查看的信息
 * @ClassName BlogArticleViewAspect
 * @Description
 * @date 2022/11/26 18:07
 * @Version 1.0
 */
@Aspect
@Slf4j
@Component
public class BlogArticleViewAspect {


    @Resource
    private RedisUtils redisUtils;

    @Resource
    private ArticleMapper articleMapper;
    /**
     * 监控浏览
     * @param joinPoint
     */
    @After(value = "execution(* com.zecan.blog.controller.ArticleController.showArticle(..))")
    public void addArticleViewAop(JoinPoint joinPoint) {
        // 获取当前线程
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        //如果当前不存在则直接跳过
        assert  attributes != null;


        HttpServletRequest request = attributes.getRequest();
        // 获取ip
        String host = request.getRemoteHost();

        Object articleId = joinPoint.getArgs()[0];

        // 查询数据库中是否存在当前文章， 如果不存在则不用保存
        if(articleMapper.checkArticleIsExist((Integer) articleId).equals(0)) {
            return;
        };

        // 根据id保存到对应的redis中 , 如果是当前第一次浏览则直接保存到redis , 如果不是当前第一次浏览则增量
        if(!Boolean.TRUE.equals(redisUtils.setIfAbsent(BlogConstant.BLOG_VIEW + articleId, 1,-1))) {
            redisUtils.incr(BlogConstant.BLOG_VIEW + articleId,1);
          }
        log.info("Ip:" + host + "访问了--->文章id:" + articleId);
    }

}
